from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from toutiao import Config
from datetime import datetime, timedelta
from auth.auth_iwt import generate_jwt


def get_user_token(user_id):
    """
    生成token
    :param user_id: 用户id
    :return: 　token(有效期两个小时) 　refresh_token(有效期１４天)
    """
    # s = Serializer(Config.SECRET_KEY, expires_in=3600)
    #
    # data = {
    #     'user_id': user_id
    # }
    #
    # return s.dumps(data).decode()

    # 设置有效期，设置当前时间
    now = datetime.utcnow()

    # 生成token
    token_expiry = now + timedelta(hours=Config.JWT_EXPIRY_HOURS)
    token = generate_jwt({'refresh': False, 'user_id': user_id}, token_expiry)

    # 生成refresh_token
    refresh_expiry = now + timedelta(days=Config.JWT_REFRESH_DAYS)
    refresh_token = generate_jwt({'refresh': True, 'user_id': user_id}, refresh_expiry)

    # 返回token
    return token, refresh_token
